import { createI18n } from 'vue-i18n'
import en from '../locales/en.json'
import zh from '../locales/zh.json'
import ja from '../locales/ja.json'
import ko from '../locales/ko.json'
import enLocale from 'element-plus/dist/locale/en.mjs'
import zhLocale from 'element-plus/dist/locale/zh-cn.mjs'
import jaLocale from 'element-plus/dist/locale/ja.mjs'
import koLocale from 'element-plus/dist/locale/ko.mjs'

// 从本地存储获取用户首选语言
// 优化后的语言映射配置
const supportedLanguages = {
  en: { code: 'en', elLocale: enLocale },
  zh: { code: 'zh-CN', elLocale: zhLocale },
  ja: { code: 'ja', elLocale: jaLocale },
  ko: { code: 'ko', elLocale: koLocale }
}

// 导出支持的语言配置
export const SUPPORTED_LOCALES = Object.values(supportedLanguages).map(lang => ({
  code: lang.code,
  name: {
    en: 'English',
    zh: '中文',
    ja: '日本語', 
    ko: '한국어'
  }[lang.code],
  flag: {
    en: '🇺🇸',
    zh: '🇨🇳',
    ja: '🇯🇵',
    ko: '🇰🇷'
  }[lang.code]
}))

const getPreferredLanguage = () => {
  const savedLang = localStorage.getItem('preferred-language')
  return savedLang ? (supportedLanguages[savedLang]?.code || 'en')
    : Object.keys(supportedLanguages).find(lang => 
        navigator.language.startsWith(lang)) || 'en'
}

// 语言切换函数
export const switchLanguage = (lang) => {
  if (!SUPPORTED_LOCALES.some(locale => locale.code === lang)) return
  i18n.global.locale.value = supportedLanguages[lang].code
  localStorage.setItem('preferred-language', lang)
}

const i18n = createI18n({
  legacy: false,
  locale: getPreferredLanguage(),
  fallbackLocale: 'en',
  messages: Object.entries(supportedLanguages).reduce((acc, [key, { elLocale }]) => {
    const localeModules = import.meta.glob('../locales/*.json', { eager: true });
    acc[supportedLanguages[key].code] = { 
      ...localeModules[`../locales/${key}.json`].default, 
      ...elLocale 
    }
    return acc
  }, {})
})

export default i18n
